package com.thb.pay.engine.groovy;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.thb.pay.core.utils.MD5SaltUtil;
import com.thb.pay.engine.InitGroovyScriptTemplate;
import com.thb.pay.engine.service.GroovyModuleRule;
import com.thb.pay.engine.service.RuleEngineGroovyExecutor;
import groovy.lang.GroovyClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class GroovyLoder implements RuleEngineGroovyExecutor<GroovyModuleRule> {
    private static final Logger log = LoggerFactory.getLogger(GroovyLoder.class);
    private Map<String, Class<GroovyModuleRule>> nameAndClass = Maps.newConcurrentMap();
    private Map<String, String> nameAndMd5 = Maps.newConcurrentMap();
    @Autowired
    private InitGroovyScriptTemplate initGroovyScriptTemplate;

    public GroovyLoder() {
    }

    public GroovyModuleRule getInstance(String name) {
        try {
            Class<GroovyModuleRule> aClass = this.nameAndClass.get(name);
            if (aClass == null) {
                throw new IllegalArgumentException(String.format("script:%s not load", name));
            } else {
                return (GroovyModuleRule) aClass.newInstance();
            }
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
    }

    public Class<GroovyModuleRule> praseAndCache(String name, String script) {
        try {
            Preconditions.checkNotNull(script);
            String scriptBuilder = this.initGroovyScriptTemplate.getScript("VaDcm2.groovy_template");
            String fullScript = String.format(scriptBuilder, script);
            String oldMd5 = this.nameAndMd5.get(name);
            String newMd5 = MD5SaltUtil.MD5(fullScript);
            if (oldMd5 != null && oldMd5.equals(newMd5)) {
                Class<GroovyModuleRule> aClass = (Class) this.nameAndClass.get(name);
                return aClass;
            } else {
                GroovyClassLoader classLoader = new GroovyClassLoader();
                Class<GroovyModuleRule> aClass = classLoader.parseClass(fullScript);
                log.info("collection-engine load script:{} finish", name);
                this.nameAndClass.put(name, aClass);
                this.nameAndMd5.put(name, newMd5);
                return aClass;
            }
        } catch (Exception var9) {
            throw new RuntimeException(var9);
        }
    }
}